//
//  TRBuyCarViewController.m
//  WeiMiLan
//
//  Created by anan on 15/8/3.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "TRBuyCarViewController.h"

@interface TRBuyCarViewController ()
{
    MJRefreshHeaderView *refreshHeaderView;
    MJRefreshFooterView *refreshFooterView;
}
@end

@implementation TRBuyCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.contents = [[NSMutableArray alloc] init];
    [self initNavigation];
    
    UINib *nib1 = [UINib nibWithNibName:@"TRBuyCarTableViewCell" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"TRBuyCarTableViewCell"];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self addHeader];
        
    self.orderDetailFootView = [[[NSBundle mainBundle] loadNibNamed:@"TROrderDetailFootView" owner:self options:nil] lastObject];
    [self.orderDetailFootView.buttonCode addTarget:self action:@selector(buttonCodeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.orderDetailFootView.textFieldCode addTarget:self action:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
    
    self.tableView.tableFooterView = self.orderDetailFootView;
    
    self.addressTableViewCell = [[[NSBundle mainBundle] loadNibNamed:@"TRAddressTableViewCell" owner:self options:nil] lastObject];
    self.addressTableViewCell.viewController = self;
    self.tableView.tableHeaderView = self.addressTableViewCell;
    [self.addressTableViewCell.buttonOk addTarget:self action:@selector(buttonAddAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self loadCoupons];
    [self loadAddress];
}

- (void)textFieldDidChange:(UITextField *)textField {
    self.couponDic = nil;
    for (NSDictionary *dic in self.coupons) {
        if ([[dic ql_stringForKey:@"CODE"] isEqualToString:self.orderDetailFootView.textFieldCode.text]) {
            self.couponDic = dic;
            break;
        }
    }
    
    [self updateCount];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [refreshHeaderView beginRefreshing];
}

- (void)buttonAddAction:(id)sender {
    TRAddressListViewController *vc = [[TRAddressListViewController alloc] init];
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refresh {
    [refreshHeaderView beginRefreshing];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"购物车";
    
    [self.weChatNavigationBar.leftButton setImage:[UIImage imageNamed:@"button_nav_back_a"] forState:UIControlStateNormal];
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(buttonBackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.weChatNavigationBar.rightButton.hidden = YES;
}

- (void)buttonBackAction:(UIButton*)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)loadData {
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/MyCart?type=11002&userId=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = resultDic[@"USER_INFO_RSP"][@"USER_CART"];
        [self.contents removeAllObjects];
        if (self.buynow) {
            if (arr.count>0) {
                [self.contents addObject:[arr lastObject]];
            }
        }else{
            [self.contents addObjectsFromArray:arr];
        }
        
        if (self.contents.count<1) {
            [SVProgressHUD showErrorWithStatus:@"购物车没有任何商品!"];
        }
        
        for (NSMutableDictionary *dic in self.contents) {
            [dic ql_setObject:QLBoolToNumber(YES) forKey:@"select"];
        }
        
        [self endRefresh];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    long count = self.contents==nil?0:self.contents.count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRBuyCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRBuyCarTableViewCell"];
    if (cell == nil) {
        cell = [[TRBuyCarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRBuyCarTableViewCell"];
    }
    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    cell.buyCarViewController = self;
    [cell setNeedsDisplay];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRBuyCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRBuyCarTableViewCell"];
    if (cell == nil) {
        cell = [[TRBuyCarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRBuyCarTableViewCell"];
    }
    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    return [cell getHeight];
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSMutableDictionary *dic = [self.contents objectAtIndex:indexPath.row];
    [QLPlayerManager openProductDetailWithId:[dic ql_stringForKey:@"ID"] viewController:self];
}

- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    refreshHeaderView = header;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadData];
    };
}

- (void)endRefresh
{
    // 刷新表格
    [self.tableView reloadData];
    [refreshFooterView endRefreshing];
    [refreshHeaderView endRefreshing];
    [self updateCount];
}

- (IBAction)buttonSelectAllAction:(UIButton*)sender {
    sender.selected = !sender.selected;
    for (NSMutableDictionary *dic in self.contents) {
        [dic ql_setObject:QLBoolToNumber(sender.selected) forKey:@"select"];
    }
    [self.tableView reloadData];
    [self updateCount];
}

- (IBAction)buttonOKAction:(id)sender {
    int count = 0;
    for (NSDictionary *dic in self.contents) {
        if ([dic ql_boolForKey:@"select"]) {
            count += [dic ql_intForKey:@"COUNT"];
        }
    }
    
    if (count<1) {
        [SVProgressHUD showErrorWithStatus:@"没有选择商品"];
        return;
    }
    
    [self buttonDoSubmitAction:sender];
}

- (void)updateCount {
    int count = 0;
    for (NSDictionary *dic in self.contents) {
        if ([dic ql_boolForKey:@"select"]) {
            count += [dic ql_intForKey:@"PRICE"]*[dic ql_intForKey:@"COUNT"];
        }
    }
    if (self.couponDic) {
        count = count + [self.couponDic ql_intForKey:@"PRICE"];
        self.orderDetailFootView.labelCount.text = [NSString stringWithFormat:@"抵￥%d元",-[self.couponDic ql_intForKey:@"PRICE"]];
    }
    NSString *strPrize = [NSString stringWithFormat:@"￥%d",count];
    NSString *str = [NSString stringWithFormat:@"合计:%@元  快递免邮",strPrize];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.325 blue:0.004 alpha:1.000] range:NSMakeRange(3, strPrize.length)];
    self.labelCount.attributedText = attributedString;
    self.labelCount.lineBreakMode = NSLineBreakByCharWrapping;
}

- (void)buttonCodeAction:(id)sender {
    UIActionSheet *ui = [[UIActionSheet alloc] initWithTitle:@"请选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    for (NSDictionary *dic in self.coupons) {
        [ui addButtonWithTitle:[dic ql_stringForKey:@"NAME"]];
    }
    [ui addButtonWithTitle:@"取消"];
    [ui showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex<self.coupons.count) {
        NSDictionary *dic = [self.coupons objectAtIndex:buttonIndex];
        self.couponDic = dic;
        [self.orderDetailFootView.buttonCode setTitle:[dic ql_stringForKey:@"NAME"] forState:UIControlStateNormal];
    }else{
        self.couponDic = nil;
        [self.orderDetailFootView.buttonCode setTitle:@"选择" forState:UIControlStateNormal];
    }
    
    [self updateCount];
}

- (void)buttonDoSubmitAction:(UIButton*)button {
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/MyOrder?type=12001&userId=%@&%@%@&phone=%@&address=%@&contact=%@&notes=%@";
    
    if (self.addressTableViewCell.labelName.text.length<2) {
        [SVProgressHUD showErrorWithStatus:@"请选择收货地址"];
        return;
    }
    
    NSString *cartIds = @"";
    for (NSDictionary *dic in self.contents) {
        if (cartIds.length<1) {
            cartIds = [NSString stringWithFormat:@"cartIds=%@",[dic ql_stringForKey:@"CART_ID"]];
        }else{
            cartIds = [NSString stringWithFormat:@"%@&cartIds=%@",cartIds,[dic ql_stringForKey:@"CART_ID"]];
        }
    }
    
    NSString *coupon = @"";
    if (self.couponDic) {
        coupon = [NSString stringWithFormat:@"&couponsIds=%@",[self.couponDic ql_stringForKey:@"ID"]];
    }
    if (coupon.length<1) {
        coupon = @"&couponsIds=";
    }
    
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,cartIds,coupon,self.addressTableViewCell.labelPhone.text,self.addressTableViewCell.labelDesc.text,self.addressTableViewCell.labelName.text,self.orderDetailFootView.textFieldRemark.text];
    
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [QLMaskUtil showMaskLoadingWithView:self.view];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        if ([QLPublic isSuccess:resultDic]) {
            [SVProgressHUD showSuccessWithStatus:@"下单成功"];
            //跳转到付款界面
            TROrderDetailViewController *vc = [TROrderDetailViewController new];
            vc.orderId = resultDic[@"USER_INFO_RSP"][@"ORDER_INFO"][0][@"ID"];
            [self presentViewController:vc animated:YES completion:nil];
        }else{
            [SVProgressHUD showErrorWithStatus:resultDic[@"MESSAGE_INFO"][@"MESSAGE"]];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

- (void)loadCoupons {
    [QLMaskUtil showMaskLoadingWithView:self.view];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/MyCoupons?type=13001&userId=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        self.coupons = resultDic[@"USER_INFO_RSP"][@"USER_COUPONS"];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

#pragma mark - TRAddressListDelegate
- (void)onAddressSelectWithInfo:(NSDictionary*)dic {
    [self.addressTableViewCell.buttonOk setBackgroundColor:[UIColor clearColor]];
    [self.addressTableViewCell.buttonOk setTitle:@"" forState:UIControlStateNormal];
    self.addressTableViewCell.info = dic;
    self.addressTableViewCell.buttonDefault.hidden = YES;
}

- (void)loadAddress {
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/UserAddress?type=14001&userId=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        NSArray *arr = resultDic[@"USER_INFO_RSP"][@"ADDRESS"];
        if (arr.count>0) {
            NSDictionary *dic = [arr firstObject];
            [self onAddressSelectWithInfo:dic];
        }
        
        for (NSDictionary *dic in arr) {
            if ([dic ql_intForKey:@"MARK"]==1) {
                [self onAddressSelectWithInfo:dic];
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

@end
